package com.aliyun.solution.demo.traffic.controller;

import com.aliyun.solution.demo.traffic.model.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * TestController
 *
 * @author yeze
 * @date 2024/09/27
 */
@Controller
@RequestMapping("/api")
public class TestController {

    @GetMapping("/normal")
    public ResponseEntity<ApiResponse> normal() {
        ApiResponse response = new ApiResponse.Builder().build();
        return ResponseEntity.ok(response);
    }

    @GetMapping("/limit")
    public ResponseEntity<ApiResponse> limit() {
        ApiResponse response = new ApiResponse.Builder().build();
        return ResponseEntity.ok(response);
    }

    @GetMapping("/breaker")
    public ResponseEntity<ApiResponse> breaker() {
        try {
            Random random = new Random();
            int delaySeconds = 1 + random.nextInt(5);
            TimeUnit.SECONDS.sleep(delaySeconds);
            if (delaySeconds % 2 == 0) {
                throw new RuntimeException("Failure");
            }
        } catch (Exception e) {
            ApiResponse errorResponse = new ApiResponse.Builder()
                    .withStatus("error")
                    .withMessage(e.getMessage())
                    .build();
            return ResponseEntity.status(500).body(errorResponse);
        }
        ApiResponse response = new ApiResponse.Builder().build();
        return ResponseEntity.ok(response);
    }

    @GetMapping("/hotspot")
    public ResponseEntity<ApiResponse> hotspot(@RequestParam String param) {
        ApiResponse response = new ApiResponse.Builder().build();
        return ResponseEntity.ok(response);
    }

    @GetMapping("/isolation")
    public ResponseEntity<ApiResponse> isolation() {
        try {
            Random random = new Random();
            int delaySeconds = 1 + random.nextInt(3);
            TimeUnit.SECONDS.sleep(delaySeconds);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return ResponseEntity.status(500).body(new ApiResponse.Builder()
                    .withStatus("error")
                    .withMessage("Internal Server Error: " + e.getMessage())
                    .build());
        }

        ApiResponse response = new ApiResponse.Builder().build();
        return ResponseEntity.ok(response);
    }
}
